package com.robaone.gwt.hierarcialdb.client.ui.admin;

import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.robaone.gwt.hierarcialdb.client.Hierarcialdbadmin;
import com.robaone.gwt.hierarcialdb.client.data.DataConstants;
import com.robaone.gwt.hierarcialdb.client.state.AdminState;

public class FileEditorUi extends Composite {

	private static FileEditorUiUiBinder uiBinder = GWT
	.create(FileEditorUiUiBinder.class);

	interface FileEditorUiUiBinder extends UiBinder<Widget, FileEditorUi> {
	}

	public FileEditorUi(HashMap<String, String> hashMap) {
		initWidget(uiBinder.createAndBindUi(this));
		this.m_data = hashMap;
		name.setText(hashMap.get("title"));
		content.setText(hashMap.get("value"));
		description.setHTML(hashMap.get("description"));
		uploadform.setMethod("POST");
		upload.setName("file");
		this.setIcon(hashMap);
	}
	public void setIcon(HashMap<String, String> info){
		Resources res =  GWT.create(Resources.class);
		int ftype = Integer.parseInt(info.get("type"));
		if(ftype == DataConstants.STRING){
			icon.setResource(res.string_file());
		}else if(ftype == DataConstants.INT){
			icon.setResource(res.number_file());
		}else if(ftype == DataConstants.DOUBLE){
			icon.setResource(res.number_file());
		}else if(ftype == DataConstants.BOOLEAN){
			icon.setResource(res.bit_file());
		}else if(ftype == DataConstants.DATETIME){
			icon.setResource(res.date_file());
		}else if(ftype == DataConstants.TEXT){
			icon.setResource(res.text_file());
		}else if(ftype == DataConstants.BINARY){
			icon.setResource(res.binary_file());
			content.setVisible(false);
			binary_area.setVisible(true);
			uploadform.setAction(Hierarcialdbadmin.getFileServletUploadUrl(info.get("id")));
		}else if(ftype == DataConstants.JSON){
			icon.setResource(res.json_file());
		}
		filename.setText(info.get("name"));
	}
	private HashMap<String, String> m_data;
	@UiField Image icon;
	@UiField InlineLabel name;
	@UiField TextArea content;
	@UiField HTML description;
	@UiField Label filename;
	@UiField Button savebutton;
	@UiField Button cancelbutton;
	@UiField Label error;
	@UiField FlowPanel binary_area;
	@UiField FormPanel uploadform;
	@UiField FileUpload upload;
	@UiField Button uploadbutton;

	@UiHandler("uploadbutton")
	public void handleUpload(ClickEvent event){
		uploadform.addSubmitCompleteHandler(new SubmitCompleteHandler(){

			@Override
			public void onSubmitComplete(SubmitCompleteEvent event) {
				String results = event.getResults();
				if(results != null && results.contains("success")){
					AdminState.showFileContents(m_data.get("id"));
				}else{
					showError("There was a problem saving your document");
				}
			}
			
		});
		uploadform.submit();
	}
	
	@UiHandler("savebutton")
	public void handleSave(ClickEvent event){
		this.error.setVisible(false);
		if(Window.confirm("Are you sure?")){
			HashMap<String,String> info = this.m_data;
			Hierarcialdbadmin.hdbService.setFileContents(content.getText(), this.m_data.get("id"), new AsyncCallback<HashMap<String,String>>(){

				@Override
				public void onFailure(Throwable caught) {
					FileEditorUi.this.showError(caught.getMessage());
				}

				@Override
				public void onSuccess(HashMap<String, String> result) {
					try{
						String status = result.get("status");
						if(DataConstants.OK_STATUS.equals(status)){
							AdminState.showFileContents(m_data.get("id"));
						}else if(DataConstants.FIELD_ERROR.equals(status)){
							throw new Exception(result.get("error"));
						}else if(DataConstants.LOGIN_REQUIRED.equals(status)){
							Window.alert("Administrative Privileges are required to make this change");
						}else if(DataConstants.ERROR.equals(status)){
							throw new Exception(result.get("error"));
						}else{
							throw new Exception("Unknown error");
						}
					}catch(Exception e){
						this.onFailure(e);
					}
				}

			});
		}
	}

	@UiHandler("cancelbutton")
	public void handleCancel(ClickEvent event){
		boolean showwarning = false;
		if(content.getText() != null && m_data.get("value") == null){
			showwarning = true;
		}else if(!content.getText().equals(m_data.get("value"))){
			showwarning = true;
		}
		if(showwarning){
			if(Window.confirm("Are you sure you want to lose your changes?")){
				AdminState.showFileContents(m_data.get("id"));
			}
		}else{
			AdminState.showFileContents(m_data.get("id"));
		}
	}
	private void showError(String string) {
		this.error.setText(string);
		this.error.setVisible(true);
	}
}
